﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NB.MGJ.Common
{
    public class CommonUtility
    {
        public static void UpdateObjectElement<T, S>(T model, Func<T, S> func, Action<T, S> action)
        {
            S obj = func(model);
            if (obj != null)
            {
                action(model, obj);
            }
        }

        /// <summary>
        /// 将一个匿名对象转换成一个字典
        /// </summary>
        /// <param name="obj">匿名对象</param>
        /// <returns>字典结果</returns>
        public static Dictionary<string, object> AnonymousObjectToDictionary(object obj)
        {
            var result = new Dictionary<string, object>();
            if (obj != null)
            {
                if (obj is Dictionary<string, object>)
                {
                    return obj as Dictionary<string, object>;
                }
                else
                {
                    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj))
                    {
                        var value = property.GetValue(obj);
                        result.Add(property.Name, value);
                    }
                }
            }
            return result;
        }

      
        public static long GetJSTimespan(DateTime dt)
        {
            TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1);
            return (long)ts.TotalMilliseconds;

        }

     
        public static DateTime GetDateTimeFromJS(long dt)
        {
            return (new DateTime(1970, 1, 1)).AddMilliseconds(dt).ToLocalTime();
        }

        public static Dictionary<string, object> AnonymousObjectToHtmlAttributes(object htmlAttributes)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();

            if (htmlAttributes != null)
            {
                foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
                {
                    result.Add(property.Name, property.GetValue(htmlAttributes));
                }
            }

            return result;
        }

        public static string FileSizeName(long length)
        {
            if (length < 1024)
            {
                return length + "字节";
            }
            else if (length < 1024 * 1024)
            {
                return length / 1024 + "KB";

            }
            else if (length < 1024 * 1024 * 1024)
            {
                return length / (1024 * 1024) + "M";

            }
            else
            {
                return "文件很大";

            }
        }

     
    }
}
